package com.resataurant.Controller.Admin;

import com.resataurant.Entity.Dish;
import com.resataurant.Service.AdminService;
import com.resataurant.Service.Impl.AdminServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@WebServlet(name = "UpdateDishServlet", value = "/UpdateDishServlet")
public class UpdateDishServlet extends HttpServlet {
    
    private static final String UPLOAD_DIRECTORY = "upload";

    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    AdminService adminService = new AdminServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");//防止中文乱码

        int sta=0;
        // 检测是否多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止上传并报错
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();//文件工程
        // 设置内存临界值
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时的存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录  添加一个路径
        String uploadPath = getServletContext().getRealPath("/") + "images";

        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        Map<Object, Object> dishMap = new HashMap<>();

        try {
            List<FileItem> dishItems = upload.parseRequest(request);
            if (dishItems != null && !dishItems.isEmpty()) {
                for (FileItem item : dishItems) {
                    if (item.isFormField()) {
                        dishMap.put(item.getFieldName(), new String(item.getString().getBytes("ISO-8859-1"), "utf-8"));
                    } else {
                        String fileName = new File(item.getName()).getName();//获取文件名字
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        String filePath = uploadPath + File.separator + uuid + ".png";

                        if (fileName.endsWith("png") || fileName.endsWith("jpg")) {//必须是这个才能上传
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            dishMap.put("img","images"+File.separator + uuid+".png");
                        } else {
                            sta=1;
                            request.getSession().setAttribute("message", "请上传png,jpg格式图片");
                            getServletContext().getRequestDispatcher("/dishDetail.jsp").forward(request, response);
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            sta=1;
            request.getSession().setAttribute("message", "请选择图片");
        }
        System.out.println(dishMap);
        Dish dish=new Dish();
        dish.setDishId((String) dishMap.get("newid"));
        dish.setDishName((String) dishMap.get("dishName"));
        dish.setDishContent((String) dishMap.get("dishContent"));
        dish.setDishPrice((String) dishMap.get("dishPrice"));
        dish.setDishImage((String) dishMap.get("img"));
        dish.setUserId((String) dishMap.get("userId"));
        String oldid=(String) dishMap.get("oldid");

        int resUpdate=adminService.updateDish(dish,oldid);
        request.getSession().setAttribute("id",dish.getDishId());
        if (resUpdate==1) {
            request.getSession().setAttribute("message", "修改成功");
        }else {
            request.getSession().setAttribute("message", "修改失败");
        }
        getServletContext().getRequestDispatcher("/dishDetail.jsp").forward(request, response);
    }
}
